package net.togogo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * .authorizeRequests() 身份认证请求
     * .anyRequest() 所有请求
     * .authenticated() 身份认证
     *
     * .disable().formLogin() 禁用springsec跨站请求伪造功能
     * .loginPage("/login") 登录页面的地址 通常是路由地址
     * .loginProcessingUrl("/auth/login") 登录表单数据提交的路径
     *
     * */

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/auth/login")
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(600) //s
                .userDetailsService(userDetailsService)
                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest()
                .authenticated();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        //项目第一次启动 需要执行 其他需要注释掉
        //tokenRepository.setCreateTableOnStartup(true);
        return tokenRepository;
    }
}
